from wifi import Cell, Scheme
import os
import time
#配置文件路径
config_path = '/home/pi/wifi.cfg'

target_cell = list()
with open(config_path,'rt') as cfg_file:
    line = cfg_file.readline()
    while line != '':
        if not line.startswith("#"):
            seps = line.split(',')
            target_cell.append((seps[0].strip(), seps[1].strip()))
        line = cfg_file.readline()
print('Configured Cells:')
for it in target_cell:
    print(it)

#kill default wpa_supplicant
print('init enviroment')
os.system('killall wpa_supplicant')
os.system('/etc/init.d/networking restart')
os.system('ifdown wlan0')
os.system('ifup wlan0')
print('init done')
# END INIT

match_cell = None
map_ssid = dict()
while match_cell is None:
    map_ssid = dict()
    for it in Cell.all('wlan0'):
        map_ssid[it.ssid] = it

    for it in target_cell:
        if it[0] in map_ssid:
            print(f'match {it[0]}')
            match_cell = it
            break
    if match_cell is None:
        print('not found... wating...')
        time.sleep(1)

print(f'connecting to {it[0]}')
scehme = Scheme.for_cell('wlan0', match_cell[0], map_ssid[match_cell[0]], match_cell[1])
#scehme.save()
scehme.activate()
#os.system('/sbin/ifdown wlan0')
#os.system(crital_cmd)
print('connected(i guess)... \n\rrunning dhcp')
os.system('/sbin/dhclient') #Maybe help
print('all done.')

# Maybe it is bad idea
time.sleep(5)
print('Start dd.service')
os.system('systemctl start dd')
print('Start remote_conn')
os.system('systemctl start remote_con')
